MATLAB="$1"
FUNCTION="$2"
ARGUMENTS="$3"
PERFORMANCE_OUTPUT="$FUNCTION""_performance.txt"

ADDPATH=""

FOLDERS="`find -type d | sed 's/.\///g' | grep -v '/' | tr '\n' ' '`"

for P in $FOLDERS;
do
    ADDPATH="addpath ./$P; $ADDPATH";
done

echo "MATLAB in $MATLAB"
echo "Current dir is $(pwd)"
find ./* -type d | grep -v "/"
echo "Running function $FUNCTION with args $ARGUMENTS"
echo "Using path: $ADDPATH"

cd $PWD

echo -e "\
$ADDPATH\
[errorRate] = $FUNCTION($ARGUMENTS);\n \
fid = fopen('$FUNCTION_performance.txt', 'w');\n \
fprintf(fid, '%d', errorRate);\n \
fclose(fid);\n \
exit;"

echo -e "\
$ADDPATH\
[errorRate] = $FUNCTION($ARGUMENTS);\n \
fid = fopen('$PERFORMANCE_OUTPUT', 'w');\n \
fprintf(fid, '%d', errorRate);\n \
fclose(fid);\n \
exit;" | $MATLAB -nodisplay 2&> matlab_output
